﻿using System;
using System.Web;
using _5E.Infrastructure.Logging;
using _5E.WebInfrastructure.Json;
using StoneAge.Controller.Handlers;
using StoneAge.Controller.Request;
using StoneAge.Controller.Storage;
using StoneAge.DataContract.Messaging;
using StructureMap;

namespace StoneAge.Controller.AsyncHandler
{
    public class AjaxAsyncHandler : IHttpAsyncHandler
    {
        public bool IsReusable { get { return true; } }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            WebRequest webRequest = ObjectFactory.GetInstance<IWebRequestFactory>().CreateWebRequestFrom(context, cb);
            try
            {
                ObjectFactory.GetInstance<IHandlerFactory>().GetHandlers().Handle(webRequest);
            }
            catch (Exception ex)
            {
                IHttpStorage storage = HttpStorageFactory.GetStorage();
                storage.Add(HttpStorageKeys.Data, new ResponseBase { Success = false, Message = "操作失败,请稍后再尝试!" });
                storage.Add(HttpStorageKeys.Exception, ex);
                webRequest.AsyncResult.SetCompleted();
            }
            return webRequest.AsyncResult;
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            IHttpStorage storage = HttpStorageFactory.GetStorage();

            if (storage.Contains(HttpStorageKeys.Exception))
                ObjectFactory.GetInstance<ILogger>().Log(storage.Retrieve(HttpStorageKeys.Exception) as Exception);

            ResponseBase response;
            if (storage.Contains(HttpStorageKeys.Offline))
                response = new ResponseBase { Success = false, Message = "无法获取数据,请重新登录!" };
            else
                response = storage.Retrieve(HttpStorageKeys.Data) as ResponseBase;

            string json = string.Empty;
            try
            {
                json = JsonHelper.ToCamelCasePropertyNameJson(response);
            }
            catch (Exception ex)
            {
                LoggingFactory.Logger.Log(ex);
                response = new ResponseBase { Success = false, Message = "未知错误,请与管理员联系!" };
                json = JsonHelper.ToCamelCasePropertyNameJson(response);
            }
            AjaxAsyncResult asyncResult = result as AjaxAsyncResult;
            asyncResult.Context.Response.Write(json);
            asyncResult.Context.Response.End();
        }

        public void ProcessRequest(HttpContext context)
        { }
    }
}
